package com.liug.droidsmall2.study.designmode;

import java.util.Observable;
import java.util.Observer;

/**
 * 观察者模式
 * Created by LG on 2018/8/20.
 */

public class ObserverMode {


    // 使用
    public void use() {

        //添加观察者
        MyObservable myObservable = new MyObservable();
        MyObserver myObserver = new MyObserver(1);
        myObservable.addObserver(myObserver);

        //改变数据
        myObservable.setName("观察者模式");
        myObservable.setAge(10);
        myObservable.setSex("男");

    }


    /**
     * 被观察者
     */
    class MyObservable extends Observable {

        private String name;
        private int age;
        private String sex;


        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
            setChanged();
            notifyObservers();
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
            setChanged();
            notifyObservers();
        }

        public String getSex() {
            return sex;
        }

        public void setSex(String sex) {
            this.sex = sex;
            setChanged();
            notifyObservers();
        }


        @Override
        public String toString() {
            return "MyPerson [name=" + name + ", age=" + age + ", sex=" + sex + "]";
        }
    }


    /**
     * 观察者
     */
    class MyObserver implements Observer {
        private int id;
        private MyObservable myObservable;

        public MyObserver(int id) {
            this.id = id;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public MyObservable getMyObservable() {
            return myObservable;
        }

        public void setMyObservable(MyObservable myObservable) {
            this.myObservable = myObservable;
        }

        @Override
        public void update(Observable observable, Object o) {
            this.myObservable = (MyObservable) observable;
        }
    }


}
